package com.tiance.web.controller.back;

import com.alibaba.fastjson.JSON;
import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.PublishInfoDO;
import com.tiance.dal.dataobject.UserDO;
import com.tiance.domainservice.checker.PublishInfoChecker;
import com.tiance.domainservice.domain.PublishInfoDomain;
import com.tiance.domainservice.service.PublishInfoService;
import com.tiance.enums.*;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.page.QueryPage;
import com.tiance.vo.PublishInfoVO;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.web.controller.base.BackController;
import com.tiance.web.controller.base.FrontController;
import com.tiance.web.controller.common.BaseResponse;
import com.tiance.web.convertor.ModelConvert;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：发布信息管理
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/back/publishInfo")
public class BackPublishInfoController extends BackController {

    private static String LOG_PREFIX ="BackPublishInfoController| 发布信息控制器===>";

    @Autowired
    private PublishInfoService publishInfoService;


    @RequestMapping(value = "/toApplyPublishInfoList.action",method = RequestMethod.GET)
    @RequiresPermissions("menu:content:publishInfo")
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到发布信息申请列表页面")
    public String toApplyPublishInfoList() {
        return "/back/content/publishInfo/publishInfoApplyList";
    }

    @RequestMapping(value = "/toPublishedInfoList.action",method = RequestMethod.GET)
    @RequiresPermissions("menu:content:publishInfo")
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到已发布信息列表页面")
    public String toPublishedInfoList() {
        return "/back/content/publishInfo/publishedInfoList";
    }






    @RequestMapping(value = "/cancel.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="取消发布信息")
    public BaseResponse cancel(HttpServletRequest request, PublishInfoVO publishInfoVO){
        logger.info("开始取消发布信息，请求参数:{}", JSON.toJSONString(publishInfoVO));
        BaseResponse<PublishInfoVO> response=new BaseResponse();

        try {
            HttpSession session=request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null!=memberId){
                publishInfoVO.setMemberId((Long)memberId);
                publishInfoVO.setApplicantId((Long)memberId);
            }

            PublishInfoChecker.checkId(publishInfoVO.getId());
            PublishInfoDomain publishInfoDomain= ModelConvert.publishInfoVO2PublishInfoDomain(publishInfoVO);
            publishInfoDomain.setInfoStatus(PublishInfoStatusEnum.INFO_CANCEL.getCode());
            if(MapCacheUtil.lock(publishInfoVO.getId() + EntityTypeEnum.PUBLISH_INFO.getCode())) {
                publishInfoService.cancel(publishInfoDomain);
                response.setSuccess(true);
                response.setMessage("取消成功!");
                response.setResult(publishInfoVO);
            }else {
                throw new BusinessException("正在操作中，请稍后再试!");
            }
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"取消发布信息失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            response.setSuccess(false);
            response.setMessage("取消失败，请稍后再试");
            logger.error(LOG_PREFIX+"取消发布信息失败,失败原因",e2);
        }finally {
            MapCacheUtil.unlock(publishInfoVO.getId() + EntityTypeEnum.PUBLISH_INFO.getCode());
        }
        logger.info("结束取消发布信息，返回数据:{}", JSON.toJSONString(publishInfoVO));
        return  response;

    }



    @RequestMapping(value = "/addPublishInfo.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="插入发布信息")
    public BaseResponse addPublishInfo( PublishInfoVO publishInfoVO){
        logger.info("开始插入发布信息，请求参数:{}", JSON.toJSONString(publishInfoVO));
        BaseResponse<PublishInfoVO> response=new BaseResponse();

        try {
            Session session = SecurityUtils.getSubject().getSession();
            UserDO userDO=(UserDO)session.getAttribute(CommonConstants.USER);
            publishInfoVO.setApplicantId(userDO.getId());
            publishInfoVO.setApplicantType(ApplicantTypeEnum.SYSTEM.getCode());

            PublishInfoChecker.addPublishInfo(publishInfoVO);
            PublishInfoDomain publishInfoDomain= ModelConvert.publishInfoVO2PublishInfoDomain(publishInfoVO);
            publishInfoDomain.setApplicantType(ApplicantTypeEnum.SYSTEM.getCode());

            publishInfoService.addPublishInfo(publishInfoDomain);
            response.setSuccess(true);
            response.setMessage("发布成功!");
            response.setResult(publishInfoVO);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"插入发布信息失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            response.setSuccess(false);
            response.setMessage("发布失败，请稍后再试");
            logger.error(LOG_PREFIX+"插入发布信息失败,失败原因",e2);
        }
        logger.info("结束插入发布信息，返回数据:{}", JSON.toJSONString(publishInfoVO));
        return  response;

    }


    @RequestMapping(value = "/publishedInfoList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="查询发布信息")
    public BaseResponse publishedInfoList( PublishInfoVO publishInfoVO, QueryPage queryPage){
        logger.info("开始查询发布信息，请求参数:{}", JSON.toJSONString(publishInfoVO));
        BaseResponse<PublishInfoDO> response=new BaseResponse();

        try {
            PublishInfoChecker.checkPageQuery(queryPage);
            publishInfoVO.setQueryPage(queryPage);
            PublishInfoDomain publishInfoDomain= ModelConvert.publishInfoVO2PublishInfoDomain(publishInfoVO);
            List<PublishInfoDO> publishInfoDOList=publishInfoService.applyPublishInfoList(publishInfoDomain);
            response.setSuccess(true);
            response.setMessage("查询成功!");
            response.setTotalRecord(publishInfoDOList.size());
            response.setQueryPage(queryPage);
            response.setResultList(publishInfoDOList);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询发布信息失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            response.setSuccess(false);
            response.setMessage("查询发布信息失败，请稍后再试");
            logger.error(LOG_PREFIX+"插入发布信息失败,失败原因",e2);
        }
        logger.info("结束查询发布信息，返回数据:{}", JSON.toJSONString(response));
        return  response;

    }


    @RequestMapping(value = "/applyPublishInfoList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="查询发布信息")
    public BaseResponse applyPublishInfoList( PublishInfoVO publishInfoVO, QueryPage queryPage){
        logger.info("开始查询发布信息，请求参数:{}", JSON.toJSONString(publishInfoVO));
        BaseResponse<PublishInfoDO> response=new BaseResponse();

        try {
            PublishInfoChecker.checkPageQuery(queryPage);
            publishInfoVO.setQueryPage(queryPage);
            List<String> status = Arrays.asList(PublishInfoStatusEnum.UN_AUDIT.getCode());
            publishInfoVO.setStatusScope(status);
            PublishInfoDomain publishInfoDomain= ModelConvert.publishInfoVO2PublishInfoDomain(publishInfoVO);
            List<PublishInfoDO> publishInfoDOList=publishInfoService.applyPublishInfoList(publishInfoDomain);
            response.setSuccess(true);
            response.setMessage("查询成功!");
            response.setTotalRecord(publishInfoDOList.size());
            response.setQueryPage(queryPage);
            response.setResultList(publishInfoDOList);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询发布信息失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            response.setSuccess(false);
            response.setMessage("查询发布信息失败，请稍后再试");
            logger.error(LOG_PREFIX+"插入发布信息失败,失败原因",e2);
        }
        logger.info("结束查询发布信息，返回数据:{}", JSON.toJSONString(response));
        return  response;

    }



    @RequestMapping(value = "/queryPublishInfoDetailById.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="查询发布信息详情")
    public BaseResponse queryPublishInfoDetailById( PublishInfoVO publishInfoVO){
        logger.info("开始查询发布信息详情，请求参数:{}", JSON.toJSONString(publishInfoVO));
        BaseResponse<PublishInfoDO> response=new BaseResponse();

        try {
            PublishInfoChecker.checkId(publishInfoVO.getId());
            PublishInfoDomain publishInfoDomain= ModelConvert.publishInfoVO2PublishInfoDomain(publishInfoVO);

            PublishInfoDO publishInfoDO=publishInfoService.queryPublishInfoDetailById(publishInfoDomain);
            response.setSuccess(true);
            response.setMessage("查询成功!");
            response.setResult(publishInfoDO);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询发布信息详情失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            response.setSuccess(false);
            response.setMessage("查询详情失败，请稍后再试");
            logger.error(LOG_PREFIX+"查询发布信息详情失败,失败原因",e2);
        }
        logger.info("查询插入发布信息详情，返回数据:{}", JSON.toJSONString(response));
        return  response;

    }


}